package com.ruoyi.common.customize.util;

import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * BigDecimal相关工具类
 *
 * @author gdk
 * @since 2022/8/16 21:58
 */
@Component
public class BigDecimalUtils {

    /**
     * 将数字转为百分比
     *
     * @param value 数字
     * @return {@link BigDecimal}
     * @author gdk
     * @since 2022/8/16 22:00
     */
    public static BigDecimal toPercent(@NotNull BigDecimal value) {
        return value.movePointLeft(2).setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 去除小数后多余的0，返回BigDecimal
     *
     * @param value 数字
     * @return {@link BigDecimal}
     * @author gdk
     * @since 2022/8/16 22:04
     */
    public static BigDecimal removeExtraZero(@NotNull BigDecimal value) {
        String str = toStrRemoveExtraZero(value);
        return BigDecimal.valueOf(Double.parseDouble(str));
    }

    /**
     * 去除小数后多余的0，返回String
     *
     * @param value 数字
     * @return {@link String}
     * @author gdk
     * @since 2022/8/16 22:04
     */
    public static String toStrRemoveExtraZero(@NotNull BigDecimal value) {
        return value.stripTrailingZeros().toPlainString();
    }

    /**
     * 将字符串转换为BigDecimal
     *
     * @param str 字符串
     * @return {@link BigDecimal}
     * @author gdk
     * @since 2022/9/16 16:09
     */
    public static BigDecimal str2BigDecimal(@NotNull String str) {
        return BigDecimal.valueOf(Double.parseDouble(str));
    }
}
